package com.qifenqian.turbot.module.ui.statistic

import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.qifenqian.turbot.R
import com.qifenqian.turbot.base.BaseFragment
import com.qifenqian.turbot.module.adapter.statistics.StatisticsHotDishAdapter
import com.qifenqian.turbot.module.contract.StatisticsContract
import com.qifenqian.turbot.module.entity.response.statistic.SoldDishEntity
import com.qifenqian.turbot.module.entity.response.statistic.StatisticsEntity
import com.qifenqian.turbot.module.presenter.StatisticsPresenter
import kotlinx.android.synthetic.main.fragment_statistics.view.*
import kotlinx.android.synthetic.main.layout_error.view.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author H
 * @createDate 2018/12/27 17:57
 * @description 首页数据页面
 * @see
 * @since
 */
private const val TYPE_DAY = 1
private const val TYPE_MONTH = 2

class StatisticsFragment : BaseFragment<StatisticsPresenter, StatisticsContract.View>(), StatisticsContract.View {


    override fun bindLayoutId(): Int {
        return R.layout.fragment_statistics
    }

    override fun bindPresenter(): StatisticsPresenter {
        return StatisticsPresenter(activity as Context, this)
    }

    private var layoutView: View? = null
    private var mSoldDishEntities = mutableListOf<SoldDishEntity>(
//            SoldDishEntity("2", 6),
//            SoldDishEntity("21", 6),
//            SoldDishEntity("4", 6),
//            SoldDishEntity("14", 6),
//            SoldDishEntity("25", 6)
                                                                 )
    private var mStatisticsHotDishAdapter: StatisticsHotDishAdapter? = null
    private var mHasDays: Boolean = true

    override fun initial(view: View) {
        layoutView = view
        view.rv_statistics_hot_dish.layoutManager = LinearLayoutManager(activity)
        mStatisticsHotDishAdapter = StatisticsHotDishAdapter(mSoldDishEntities)
        view.rv_statistics_hot_dish.adapter = mStatisticsHotDishAdapter
        view.rg_statistics.check(R.id.rb_statistics_day)
        view.tv_statistics_date.text = getCurrentDate()
        mPresenter!!.getBusinessStatistics(getCurrentDate(), TYPE_DAY)
        mPresenter!!.getDishStatistics(getCurrentDate(), TYPE_DAY)
        view.rg_statistics.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_statistics_day   -> {
                    mHasDays = true
                    view.rb_statistics_day.textSize = 28f
                    view.rb_statistics_month.textSize = 20f
                    view.tv_statistics_date.text = getTime(Date(System.currentTimeMillis()))
                    mPresenter!!.getBusinessStatistics(getCurrentDate(), TYPE_DAY)
                    mPresenter!!.getDishStatistics(getCurrentDate(), TYPE_DAY)
                }
                R.id.rb_statistics_month -> {
                    mHasDays = false
                    view.rb_statistics_day.textSize = 20f
                    view.rb_statistics_month.textSize = 28f
                    view.tv_statistics_date.text = getTime(Date(System.currentTimeMillis()))
                    mPresenter!!.getBusinessStatistics(getCurrentDate(), TYPE_MONTH)
                    mPresenter!!.getDishStatistics(getCurrentDate(), TYPE_MONTH)
                }
            }
        }
        view.tv_statistics_date.setOnClickListener {
            showDatePickDialog(view.tv_statistics_date)
        }
        view.btn_statistics_notification.setOnClickListener {
            // TODO: 2019/1/15 通知界面
        }
    }

    private fun getCurrentDate() = getTime(Date(System.currentTimeMillis()))

    private fun showDatePickDialog(tv: TextView) {
        val pvTime = TimePickerBuilder(activity, OnTimeSelectListener { date, v ->
            tv.text = getTime(date)
            mPresenter!!.getBusinessStatistics(getCurrentDate(), if (mHasDays) TYPE_DAY else TYPE_MONTH)
            mPresenter!!.getDishStatistics(getCurrentDate(), if (mHasDays) TYPE_DAY else TYPE_MONTH)
        }).setTimeSelectChangeListener { Log.i("pvTime", "onTimeSelectChanged") }
                .setType(booleanArrayOf(true, true, mHasDays, false, false, false))
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build()
        val dialog = pvTime.dialog
        if (dialog != null) {
            val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM)
            params.leftMargin = 0
            params.rightMargin = 0
            pvTime.dialogContainerLayout.layoutParams = params
            val dialogWindow = dialog.window
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim)//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM)//改成Bottom,底部显示
            }
        }
        dialog.show()
    }

    private fun getTime(date: Date): String {//可根据需要自行截取数据显示
        val format = SimpleDateFormat(if (mHasDays) {
            "yyyy-MM-dd"
        } else {
            "yyyy-MM"
        })
        return format.format(date)
    }

    override fun getBusinessStatisticsResult(isSuccess: Boolean, code: Int, msg: String?, statisticsEntity: StatisticsEntity?) {
        if (isSuccess) {
            if (statisticsEntity != null) {
                layoutView!!.tv_statistics_transaction.text = statisticsEntity.turnover
                layoutView!!.tv_statistics_order_number.text = statisticsEntity.orders
                layoutView!!.tv_statistics_visitor_number.text = statisticsEntity.visits
                layoutView!!.tv_statistics_order_price.text = (statisticsEntity.averageOrderPrice / 100).toString() + "元"
            } else {
                layoutView!!.ly_statistics_data.removeAllViews()
                LayoutInflater.from(activity!!).inflate(R.layout.layout_empty, layoutView!!.ly_statistics_data)
            }
        } else {
            layoutView!!.ly_statistics_data.removeAllViews()
            val view = LayoutInflater.from(activity!!).inflate(R.layout.layout_error, layoutView!!.ly_statistics_data)
            view.btn_error_retry.setOnClickListener {
                mPresenter!!.getBusinessStatistics(getCurrentDate(), if (mHasDays) TYPE_DAY else TYPE_MONTH)
            }
        }
    }

    override fun getDishStatisticsResult(isSuccess: Boolean, code: Int, msg: String?, soldDishEntities: List<SoldDishEntity>?) {
        if (isSuccess) {
            if (!soldDishEntities.isNullOrEmpty()) {
                mSoldDishEntities.clear()
                mSoldDishEntities.addAll(soldDishEntities as MutableList)
                mStatisticsHotDishAdapter!!.notifyDataSetChanged()
            } else {
                val view = LayoutInflater.from(activity!!).inflate(R.layout.layout_empty, layoutView!!.rv_statistics_hot_dish)
                mStatisticsHotDishAdapter!!.emptyView = view
            }
        } else {
            val view = LayoutInflater.from(activity!!).inflate(R.layout.layout_error, layoutView!!.rv_statistics_hot_dish, false)
            mStatisticsHotDishAdapter!!.emptyView = view
            view.btn_error_retry.setOnClickListener {
                mPresenter!!.getDishStatistics(getCurrentDate(), if (mHasDays) TYPE_DAY else TYPE_MONTH)
            }
        }
    }

}
